<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<div id="chord-chart"></div>
<script>
    // 获取容器元素
    const container = document.getElementById('chord-chart');

    // 定义数据
    const matrix = [
        [11975, 5871, 8916, 2868],
        [1951, 10048, 2060, 6171],
        [8010, 16145, 8090, 8045],
        [1013, 990, 940, 6907]
    ];

    // 定义颜色比例尺
    const color = d3.scaleOrdinal()
        .range(d3.schemeCategory10);

    // 创建chord布局
    const chord = d3.chord()
        .padAngle(0.05)
        .sortSubgroups(d3.descending);

    // 计算chord布局所需的数据
    const chords = chord(matrix);

    // 创建SVG画布
    const width = 400;
    const height = 400;
    const svg = d3.select(container)
        .append('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', `translate(${width / 2}, ${height / 2})`);

    // 绘制弧形路径
    const arc = d3.arc()
        .innerRadius(150)
        .outerRadius(160);

    // 绘制弦路径
    const ribbon = d3.ribbon()
        .radius(150);

    // 绘制弧形
    const arcs = svg.selectAll('g')
        .data(chords.groups)
        .enter()
        .append('g');

    arcs.append('path')
        .attr('fill', (d) => color(d.index))
        .attr('d', arc);

    // 添加节点标签
    arcs.append('text')
        .each((d) => {
            d.angle = (d.startAngle + d.endAngle) / 2;
        })
        .attr('dy', '.35em')
        .attr('transform', (d) => `
    rotate(${(d.angle * 180 / Math.PI - 90)})
    translate(${arc.centroid(d)})
    ${d.angle > Math.PI ? 'rotate(180)' : ''}
  `)
        .style('text-anchor', (d) => d.angle > Math.PI ? 'end' : null)
        .text((d, i) => `Node ${i + 1}`);


    // 绘制弦
    svg.append('g')
        .attr('fill-opacity', 0.7)
        .selectAll('path')
        .data(chords)
        .enter()
        .append('path')
        .attr('fill', (d) => color(d.target.index))
        .attr('d', ribbon);
</script>
</body>
</html>